package com.gh.rabbitmq.one;

import com.rabbitmq.client.*;

import java.io.IOException;
import java.util.concurrent.TimeoutException;

/**
 * @Author Eric
 * @Date 2021/7/17 16:13
 * @Version 1.0
 * 消費者,接收消息
 */
public class Consumer {
    //队列名称
    public static final String QUEUE_NAME = "hello";
    //接收消息
    public static void main(String[] args) throws IOException, TimeoutException {
        ConnectionFactory factory=new ConnectionFactory();
        //设置ip 用户名 密码
        factory.setHost("192.168.1.11");
        factory.setUsername("guest");
        factory.setPassword("guest");
        //创建连接
        Connection connection=factory.newConnection();
        //创建信道
        Channel channel = connection.createChannel();
        //声明接收消息
        DeliverCallback deliverCallback=(consumerTag,message)->{
            System.out.println(new String(message.getBody()));
        };
        //取消消息时的回调
        CancelCallback cancelCallback=consumerTag->{
            System.out.println("消费消息被中断了");
        };
        /**
         * 消费者消费消息
         *  1.消费哪个队列
         *  2.消费成功之后是否要自动应答,true代表自动应答
         *  3.消费者未成功消费的回调
         *  4.消费者取消回调
         *
         */
        channel.basicConsume(QUEUE_NAME,true,deliverCallback,cancelCallback);
    }
}
